package com.d3works.apps.base.rest.http;

import com.d3works.apps.base.rest.common.R;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.util.Collection;
import java.util.List;
import java.util.Map;

public class ResponseEventArgs {

  private InputStream responseStream;

  private final HttpURLConnection conn;

  private int responseCode;

  private String responseMessage;

  private String responseText;

  private String redirectTo;

  public ResponseEventArgs(HttpURLConnection conn) {
    this.conn = conn;
    try {
      responseCode = this.conn.getResponseCode();
      if (responseCode == 302) {
        redirectTo = this.conn.getHeaderField("Location");
      } else if (responseCode == 500) {
        responseMessage = R.readText(this.conn.getErrorStream(), "UTF-8", true);
        return;
      }
    } catch (IOException e) {
      responseCode = 500;
      responseMessage = "IO异常：" + e.getMessage();
    }
  }

  public synchronized InputStream getResponseStream() throws IOException {
    if (responseCode != 200) {
      throw new IOException(responseMessage);
    }
    if (responseStream == null) {
      responseStream = conn.getInputStream();
    }
    return responseStream;
  }

  public synchronized String getResponseText() throws IOException {
    if (responseCode != 200) {
      return this.responseMessage;
    }
    if (responseText == null) {
      InputStream in = conn.getInputStream();
      responseText = R.readText(in, "UTF-8", true);
    }
    return responseText;
  }

  public int getResponseCode() {
    return responseCode;
  }

  public boolean isSuccess() {
    return responseCode == 200;
  }

  public String getResponseMessage() {
    return responseMessage;
  }

  public String getRedirectTo() {
    return redirectTo;
  }

  public Map<String, List<String>> headers() {
    Map<String, List<String>> map = conn.getHeaderFields();
    return map;
  }

  public String header(String name) {
    List<String> values = headers().get(name);
    if (values == null) {
      return null;
    }
    return join(values, ",");
  }

  public static String join(Collection<String> coll, String joiner) {
    return null;
  }
}
